<template>
	<view class="add-device">
		<!-- <uni-load-more status="more"></uni-load-more> -->
		<up-card :show-head="false" :show-foot="false">
			<template #body>
				<view class="devide-search" slot="body">
					<view class="devide-search-title">
						扫描附近的设备
					</view>
					<up-loading-icon :show="searching" text="持续自动搜索中" textSize="12" size="13"></up-loading-icon>
					<view class="devide-search-contain" v-for="(item,index) in devices" :key="index">
						<view class="devide-search-contain-item">
							<view class="devide-search-contain-item-name">
								设备名称：{{item.localName}}
							</view>
							<view class="devide-search-contain-item-addIcon" @click="goAddDevice(item)">
								<image src="@/static/icons/add3251c0.png" mode="aspectFit"
									style="width: 40rpx; height: 40rpx;">
								</image>
							</view>
						</view>

					</view>
				</view>
			</template>

		</up-card>
		<up-card :show-head="false" :show-foot="false">
			<template #body>
				<view class="devide-add-icon" slot="body">
					<view class="devide-add-icon-scan" @click="scanAdd">
						<view class="devide-add-icon-bg">
							<image src="@/static/icons/u41.png" mode="aspectFit" style="width: 50px; height: 50px;">
							</image>
						</view>
						<view class="">
							扫码添加
						</view>
					</view>
					<!-- 手动添加先注释掉，用的时候再打开 -->
					<view class="devide-add-icon-self" @click="goAddManually">
						<view class="devide-add-icon-bg">
							<image src="@/static/icons/u43.png" mode="aspectFit" style="width: 50px; height: 50px;">
							</image>
						</view>
						<view class="">
							手动添加
						</view>
					</view>
				</view>
			</template>

		</up-card>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onShow,
		onUnload,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {
		BluetoothStore
	} from '@/store/Bluetooth.js'
	const blueStore = BluetoothStore()

	const bluetoothEnabled = ref(false) // 蓝牙是否开启
	const searching = ref(false) // 是否正在搜索
	const devices = ref([]) // 搜索到的设备列表
	const targetDevices = ref([]) // 筛选后的目标设备列表
	const connectedDeviceId = ref('') // 已连接设备ID
	const connecting = ref(false) // 是否正在连接
	const bluetoothStatus = ref(false) // 是否正在连接
	const errMsg = ref('搜索附近设备')
	onShow(async (e) => {
		devices.value = [];
		initBluetooth();
		wx.onBluetoothAdapterStateChange((res) => {
			if (res.discovering) {
				searching.value = true
			} else {
				searching.value = false
			}
		})
	})

	onUnload(() => {
		// 生命周期函数：页面卸载时关闭蓝牙连接和模块
		wx.closeBluetoothAdapter({
			success(res) {
				console.log('关闭蓝牙模块', res)
			}
		})

	})

	onPullDownRefresh(() => {
		//这里不需要下拉动画 直接关了就行
		uni.stopPullDownRefresh();
		searching.value = true;
		startFindDevice()
		//显示模拟搜索
		// setTimeout(() => {
		// 	devices.value.push({
		// 		localName: '模拟空调设备',
		// 		deviceId: '978-7-89391-343-7'
		// 	})
		// }, 1000);
		setTimeout(() => {
			stopFindDevice()
		}, 20000);
	})

	// 初始化蓝牙模块
	const initBluetooth = async () => {
		wx.openBluetoothAdapter({
			success: () => {
				startFindDevice();
			},
			fail: (e) => {
				console.log(e, '初始化失败')
				uni.showToast({
					title: '请手动开启蓝牙',
					icon: 'none'
				})

			}
		})
	}

	const startFindDevice = () => {
		//默认一轮搜索持续20s
		setTimeout(() => {
			stopFindDevice()
		}, 20000);
		// 开始扫描设备
		wx.startBluetoothDevicesDiscovery({
			// services: ['0000FFFF-0000-1000-8000-00805F9B34FB'], // 目标设备的服务UUID
			success: (res) => {
				searching.value = true;
				wx.onBluetoothDeviceFound((ds) => {
					console.log(ds, '发现设备')
					if (ds.devices[0].localName.includes("BLUFI")) {
						devices.value.push(ds.devices[0])
					}
				})
			},
			fail(e) {
				searching.value = false;
				errMsg.value = JSON.stringify(e)
				console.log(e, '查找失败')
			}
		})
	}

	const stopFindDevice = () => {
		searching.value = false;
		wx.stopBluetoothDevicesDiscovery();
	}

	const goAddDevice = (val) => {
		console.log(val.deviceId, "选中连接的设备")
		// let data = {
		// 	deviceId:val.deviceId,
		// 	serviceId:'3441564561',
		// 	characteristicId:'777897897'
		// }
		// uni.setStorageSync('selectedDev',data)
		// uni.navigateTo({
		// 	url: "/Device/chooseWifi/chooseWifi"
		// })
		uni.showLoading({
			title: "连接中..."
		})
		// 连接设备
		wx.createBLEConnection({
			deviceId: val.deviceId,
			success: (res) => {
				console.log('设备已连接')

				stopFindDevice();
				wx.getBLEDeviceServices({
					deviceId: val.deviceId,
					success: function(Services) {
						console.log('设备服务', Services)
						const serviceId = Services.services[0].uuid;
						wx.getBLEDeviceCharacteristics({
							deviceId: val.deviceId,
							serviceId: serviceId,
							success: function(Characteristics) {
								console.log('设备特征值', Characteristics)
								const characteristicId = Characteristics
									.characteristics[0].uuid;
								let data = {
									localName: val.localName,
									uid: val.advertisServiceUUIDs[0],
									deviceId: val.deviceId,
									serviceId: serviceId,
									characteristicId: characteristicId
								}
								blueStore.setDeviceInfo(data)
								uni.setStorageSync('selectedDev', data)
								uni.hideLoading()
								uni.navigateTo({
									url: "/Device/chooseWifi/chooseWifi?"
								})
							}
						})

					}
				})
			},
			fail: (e) => {
				console.log('设备连接失败', e)
			}
		})

	}

	// 手动添加
	const goAddManually = () => {
		uni.navigateTo({
			url: `/Device/AddManually/AddManually`
		})
	}
	// 处理扫码结果
	const handleScanResult = (result) => {
		if (result) {
			const encodedUid = encodeURIComponent(result);
			uni.navigateTo({
				url: `/Device/AddManually/AddManually?uid=${encodedUid}&&isQr=true`
			})
		}
	}
	//请求相机权限
	const requestCameraPermission = async () => {
		try {
		    await uni.authorize({
		      scope: "scope.camera",
		    });
		    // 权限获取成功后直接调用扫码
		    uni.scanCode({
		      onlyFromCamera: false,
		      autoZoom: true,
		      scanType: ["qrCode", "pdf417", "datamatrix", "barCode"],
		      autoDecodeCharset: true,
		      success: (res) => {
		        handleScanResult(res.result);
		      },
		    });
		  } catch (err) {
		    uni.showModal({
		      title: "权限提示",
		      content: "需要相机权限才能使用扫码功能，是否前往设置开启？",
		      confirmText: "去设置",
		      success: (res) => {
		        if (res.confirm) {
		          uni.openSetting();
		        }
		      },
		    });
		  }
	}
	const scanAdd = async () => {
		const res = await uni.getSetting()
		if (res.authSetting['scope.camera']) {
			uni.scanCode({
				onlyFromCamera: false, // 只允许相机扫码
				autoZoom: true,
				scanType: ['qrCode', 'pdf417', 'datamatrix', 'barCode'],
				autoDecodeCharset: true,
				success: (res) => {
					handleScanResult(res.result)
				}
			})
		} else {
			// 自动请求权限
			await requestCameraPermission()
		}
	}
</script>

<style lang="scss" scoped>
	@import "./addDevice.scss";
</style>